﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
using System.Web;
using System.Web.SessionState;
using DTcms.Web.UI;
using DTcms.Common;
using DTcms.API.Payment.wxpay;

namespace DTcms.Web.m
{
    /// <summary>
    /// get_orderid 的摘要说明
    /// </summary>
    public class get_orderid : IHttpHandler, IRequiresSessionState
    {

        public void ProcessRequest(HttpContext context)
        {
            //检查用户是否登录
            string user_name = DTRequest.GetFormString("txtUserName");
            string user_pwd = DTRequest.GetFormString("txtPassword");
            /// Demon 添加 20200228 手机系统类型  
            /// ios
            /// android       
            /// win             //Windows系统   
            /// wp              //Windows Phone系统
            string _systemType = DTRequest.GetString("systemType");

            if (string.IsNullOrEmpty(user_name) || string.IsNullOrEmpty(user_pwd))
            {
                context.Response.Write("{\"status\":0, \"msg\":\"您的登录信息有误，请退出系统后重新登录！\"}");
                return;
            }
            Model.users userModel = new BLL.users().GetModel(user_name, user_pwd, 0, 1, true);
            if (userModel == null)
            {
                context.Response.Write("{\"status\":0, \"msg\":\"您的登录信息有误，请退出系统后重新登录！\"}");
                return;
            }
         

            int _group_id = DTRequest.GetInt("group_id", 0);
            string _parent_mobile = DTRequest.GetFormString("txtParentMobile");
            if (_group_id == 0)
            {
                context.Response.Write("{\"status\": 0, \"msg\": \"错误提示：未指定升级ID！\"}");
                return;
            }

            //Demon 20200229 取消IOS端认证会员的支付，直接返回支付失败！
            if (_group_id==2)// && _systemType != "android" && !string.IsNullOrWhiteSpace(_systemType)
            {
                context.Response.Write("{\"status\":0, \"msg\":\"认证会员已取消，目前平台只支持vip会员！\"}");
                return;
            }
            string _body = string.Empty;
            decimal _amount = 0M;
            //switch (_group_id)
            //{
            //    case 2:
            //        _body = "开通298元VIP会员";
            //        _amount = 298;
            //        break;
            //    case 3:
            //        _body = "开通2880元钻石会员";
            //        _amount = 2880;
            //        break;
            //}
            #region///Demon 修改 获取会员价格的方式 从会员级别表中获取
            ///Demon 修改 获取会员价格的方式 从会员级别表中获取
            BLL.user_groups ugbll = new BLL.user_groups();
            Model.user_groups ugmodel = ugbll.GetModelByGrage(_group_id);
            _body = "开通" + ugmodel.price + ugmodel.title;
            _amount = ugmodel.price;
            #endregion 


            string _order_no = "M" + Utils.GetOrderNumber();

            BLL.member_order bll = new BLL.member_order();
            Model.member_order model = new Model.member_order();

            model.order_no = _order_no;
            model.user_id = userModel.id;
            model.group_id = _group_id;
            model.amount = _amount;
            model.add_time = DateTime.Now;
            model.payment_id = 1;
            model.remark = _body;
            model.parent_mobile = _parent_mobile;

            int result = bll.Add(model);
            if (result==0)
            {
                context.Response.Write("{\"status\": 0, \"msg\": \"错误提示：保存订单时出错！\"}");
                return;
            }
            Utils.WriteTextLog("get_orderid", "_order_no:" + _order_no , DateTime.Now);
            //第一步先生成一个签名
            string sendUrl = "https://api.mch.weixin.qq.com/pay/unifiedorder";
            WxPayData data = new WxPayData();
            data.SetValue("body", _body); //商品描述
            data.SetValue("out_trade_no", _order_no); //商户订单号
            data.SetValue("total_fee", (Convert.ToDouble(_amount) * 100).ToString()); //订单总金额,以分为单位
            data.SetValue("trade_type", "APP");//交易类型
            data.SetValue("notify_url", "http://www.shicaiquanzi.com/payment/notify_url.aspx"); //异步通知url
            data.SetValue("spbill_create_ip", DTRequest.GetIP()); //终端IP
            data.SetValue("appid", "wxf3b482c702bdb291"); //公众账号ID
            data.SetValue("mch_id", "1504256031"); //商户号
            data.SetValue("nonce_str", GenerateNonceStr()); //随机字符串
            //data.SetValue("sign", data.MakeSign("SrdyeR5v23cClIsgI0Dvs5UwCCOTXSa7")); //签名
            data.SetValue("sign", data.MakeSign("N8iTCQt8Ob2Fw6Yud4VIRnNaXJHllEfN")); //签名
           
            string xml = data.ToXml(); //转换成XML
            Utils.WriteTextLog("get_orderid", "data" + xml, DateTime.Now);
            string response = HttpService.Post(xml, sendUrl, false, 6); //发送请求
            
            Utils.WriteTextLog("get_orderid", "response:" + response, DateTime.Now);
            WxPayData wd = new WxPayData();
            wd.FromXml(response);
            if (wd.GetValue("return_code").ToString() == "SUCCESS")
            {
                //开始组织微信需要的结构
                WxPayData newdata = new WxPayData();
                newdata.SetValue("appid", wd.GetValue("appid").ToString());
                newdata.SetValue("partnerid", "1504256031");
                newdata.SetValue("prepayid", wd.GetValue("prepay_id").ToString());
                newdata.SetValue("package", "Sign=WXPay");
                newdata.SetValue("noncestr", GenerateNonceStr());
                newdata.SetValue("timestamp", GenerateTimeStamp());
                //newdata.SetValue("sign", newdata.MakeSign("SrdyeR5v23cClIsgI0Dvs5UwCCOTXSa7"));
                newdata.SetValue("sign", newdata.MakeSign("N8iTCQt8Ob2Fw6Yud4VIRnNaXJHllEfN"));
                string json_str = newdata.ToJson();
                StringBuilder strTxt = new StringBuilder();
                strTxt.Append("{");
                strTxt.Append("\"status\":1");
                strTxt.Append(",\"payData\":" + json_str);
                strTxt.Append("}");
                Utils.WriteTextLog("get_orderid", strTxt.ToString(), DateTime.Now);
                context.Response.Write(strTxt.ToString());
            }
            else
            {
                context.Response.Write("{\"status\": 0, \"msg\": \"支付过程中遇至未知错误，请重试！\"}");
            }


            //StringBuilder strTxt = new StringBuilder();
            //strTxt.Append("{");
            //strTxt.Append("\"status\":1");
            //strTxt.Append(",\"pay_result\":{");
            //strTxt.Append("\"apikey\":\"" + wd.GetValue("appid").ToString() + "\"");
            //strTxt.Append(",\"prepay_id\":\"" + wd.GetValue("prepay_id").ToString() + "\"");
            //strTxt.Append(",\"mch_id\":\"" + wd.GetValue("mch_id").ToString() + "\"");
            //strTxt.Append(",\"nonce_str\":\"" + wd.GetValue("nonce_str").ToString() + "\"");
            //strTxt.Append(",\"timestamp\":\"" + GenerateTimeStamp() + "\"");
            //strTxt.Append(",\"sign\":\"" + wd.GetValue("prepay_id").ToString() + "\"");
            //strTxt.Append("}");
            //strTxt.Append("}");
            
        }
        /**
       * 生成随机串，随机串包含字母或数字
       * @return 随机串 
       */
        public string GenerateNonceStr()
        {                
            return Guid.NewGuid().ToString().Replace("-", "");
        }
        /**
        * 生成时间戳，标准北京时间，时区为东八区，自1970年1月1日 0点0分0秒以来的秒数
         * @return 时间戳
        */
        public static string GenerateTimeStamp()
        {
            TimeSpan ts = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0);
            return Convert.ToInt64(ts.TotalSeconds).ToString();
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}